<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入单据编号"
          clearable
          size="small"
          style="width: 250px;"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品信息" prop="material">
        <el-input
          v-model="queryParams.material"
          placeholder="请输入条形码、名称、规格、型号"
          clearable
          size="small"
          style="width: 250px;"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据日期" prop="operTimeRange">
        <el-date-picker clearable size="small"
          v-model="queryParams.operTimeRange"
          style="width: 250px;"
          type="daterange"
          value-format="yyyy-MM-dd"
          placeholder="选择单据日期">
        </el-date-picker>
      </el-form-item>
      <template v-if="toggleSearchStatus">
      <el-form-item label="供应商" prop="organId">
        <el-select
          v-model="queryParams.organId"
          placeholder="请选择供应商"
          clearable
		  filterable
          size="small"
          style="width: 250px;"
        >
          <el-option
            v-for="menber in members"
            :key="menber.id"
            :label="menber.supplier"
            :value="menber.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作员" prop="creator">
        <el-select
          v-model="queryParams.creator"
          placeholder="请选择操作员"
          clearable
          size="small"
          style="width: 250px;"
        >
          <el-option
            v-for="user in users"
            :key="user.userId"
            :label="user.nickName"
            :value="user.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      </template>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        <el-button type="text" size="small" style="margin-left: 8px" @click="handleToggleSearch" >{{ toggleSearchStatus ? '收起' : '展开' }}<i v-if="toggleSearchStatus" class="el-icon-arrow-up"></i><i v-else-if="!toggleSearchStatus" class="el-icon-arrow-down"></i></el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['bill:purchaseorder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown @command="handleCommand">
          <el-button :disabled="multiple" size="small" type="danger">
            批量操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="delete" v-hasPermi="['bill:purchaseorder:remove']"><i class="el-icon-delete"></i>删除</el-dropdown-item>
            <el-dropdown-item command="enabled" v-hasPermi="['bill:purchaseorder:check']" ><i class="el-icon-document-checked"></i>审核</el-dropdown-item>
            <el-dropdown-item command="disabled" v-hasPermi="['bill:purchaseorder:unCheck']"><i class="el-icon-document-delete"></i>反审核</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>

    <el-table v-loading="loading" max-height="620px" :data="retailList" @selection-change="handleSelectionChange" @row-dblclick="myHandleDetail">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" v-if="false" prop="id" />
      <el-table-column label="供应商"  prop="organId" :formatter="organFormat"  width="200" />
      <el-table-column label="单据编号"  prop="number" width="185"/>
      <el-table-column label="商品信息"  prop="material" :show-overflow-tooltip="true"/>
      <el-table-column label="单据时间" align="center" prop="operTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作员" align="center" prop="creator" :formatter="creatorFormat" />
      <el-table-column label="金额合计" align="center" prop="totalPrice" width="120"/>
      <el-table-column label="含税合计" align="center" prop="changeAmount" width="120"/>
      <el-table-column label="状态" align="center" prop="status" width="80">
       <template slot-scope="scope">
         <dict-tag :options="dict.type.depot_head_status" :value="scope.row.status"/>
       </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            @click="myHandleDetail(scope.row)"
            v-hasPermi="['bill:purchaseorder:edit']"
          >查看</el-button>
          <el-button
            size="small"
            type="text"
            v-if="scope.row.status==0"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bill:purchaseorder:edit']"
          >修改</el-button>
          <el-button
            size="small"
            type="text"
            @click="handleCopy(scope.row)"
            v-hasPermi="['bill:purchaseorder:copy']"
          >复制</el-button>
<!--          <el-button
            size="small"
            type="text"
            @click="handleCopyAdd(scope.row)"
            v-hasPermi="['bill:purchaseorder:add']"
          >出库</el-button> -->
          <el-button
            size="small"
            type="text"
            v-if="scope.row.status==0"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bill:purchaseorder:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改单据管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <el-row>
          <el-col :span="6">
            <el-form-item label="供应商" prop="organId" label-width="100px">
              <el-select
                v-model="form.organId"
                placeholder="请选择供应商"
                clearable
				filterable
                size="small"
                style="width: 100%;"
                ref="organSelect"
                @visible-change="v => visibleChange(v,'organSelect', addOrganClick, '添加供应商')"
              >
                <el-option
                  v-for="menber in members"
                  :key="menber.id"
                  :label="menber.supplier"
                  :value="menber.id"
                >
                  <span style="float: left" class="span-style">{{ menber.supplier }}</span>
                  <div class="flag" style="float: left;">
                    <svg-icon icon="edit" iconClass="template_edit_style" />
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据编号" prop="defaultNumber" label-width="100px">
              <el-input v-model="form.defaultNumber" readonly />
            </el-form-item>
           <!-- <el-form-item label="票据号" prop="number">
              <el-input v-model="form.number" placeholder="请输入票据号" />
            </el-form-item> -->
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据时间" prop="operTime"  label-width="100px">
              <el-date-picker clearable size="small"  style="width: 100%;"
                v-model="form.operTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择单据时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="24">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAddZnDepotItem">新增行</el-button>
              </el-col>
              <!-- <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="small" >扫码录入（待开发）</el-button>
              </el-col> -->
              <el-col :span="1.5">
                <el-button
                  type="info"
                  plain
                  icon="el-icon-upload2"
                  size="small"
                  @click="handleImport"
                >导入</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" :disabled="depot.multiple" icon="el-icon-delete" size="small" @click="handleDeleteZnDepotItem">删除</el-button>
              </el-col>
            </el-row>
              <el-table :data="form.znDepotItemList" :row-class-name="rowZnDepotItemIndex" @selection-change="handleZnDepotItemSelectionChange" ref="znDepotItem" show-summary :summary-method="getItemSummaries" size="small" :max-height="380">
                <!-- <el-table-column label="序号" align="center" prop="index" width="50" /> -->
                <el-table-column type="selection" width="50" align="center" class-name="allowDrag"/>
                <el-table-column label="条码" prop="barCode" width="120" align="center" style="padding-left: 0px;padding-right: 0rem;">
                  <template slot-scope="scope">
                    <el-input
                        placeholder="请选择"
                        v-model="scope.row.barCode" size="small">
                        <i slot="suffix" class="el-input__icon el-icon-search" @click="handleSelectMaterial(scope.row,scope.$index)"></i>
                      </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="名称" prop="materialId"  width="120" align="center">
                  <template slot-scope="scope">
                    <input type="hidden" v-model="scope.row.materialId" />
                    <el-input size="small" v-model="scope.row.materialName" class="dashed" readonly/>
                  </template>
                </el-table-column>
                <el-table-column label="规格" prop="standard"  width="80" align="center">
                  <template slot-scope="scope">
                    <el-input size="small" v-model="scope.row.standard" class="dashed" readonly/>
                  </template>
                </el-table-column>
                <el-table-column label="型号" prop="model"  width="80" align="center" v-if="isModel" >
                  <template slot-scope="scope">
                    <el-input size="small" v-model="scope.row.model" class="dashed" readonly/>
                  </template>
                </el-table-column>
                <el-table-column label="颜色" prop="color"  width="80" align="center" v-if="isColor" >
                  <template slot-scope="scope">
                    <el-input size="small" v-model="scope.row.color" class="dashed" readonly/>
                  </template>
                </el-table-column>
                <el-table-column label="扩展信息" prop="mfrs"  width="100" align="center" v-if="isMfrs">
                  <template slot-scope="scope">
                    <el-input size="small" v-model="scope.row.mfrs" class="dashed" readonly/>
                  </template>
                </el-table-column>
                <el-table-column label="库存" prop="currentNumber"  width="60" align="center">
                  <template slot-scope="scope">
                    <el-input size="small" v-model="scope.row.currentNumber" class="dashed" readonly/>
                  </template>
                </el-table-column>
                <el-table-column label="单位" prop="materialUnit" width="60" align="center">
                  <template slot-scope="scope">
                    <el-input size="small" v-model="scope.row.materialUnit" class="dashed" readonly/>
                  </template>
                </el-table-column>
                <el-table-column label="多属性" prop="sku" width="100" align="center" v-if="isSku">
                  <template slot-scope="scope">
                    <el-input size="small" v-model="scope.row.sku" class="dashed"  readonly/>
                  </template>
                </el-table-column>
                <el-table-column label="序列号" prop="materialSerialNumber" width="100" align="center" v-if="isSerialNumber">
                <!--  <template slot-scope="scope">
                    <el-input v-model="scope.row.materialSerialNumber" />
                  </template> -->
                  <template slot-scope="scope">
                    <el-input
                        placeholder="请选择"
                        v-model="scope.row.materialSerialNumber" size="small">
                        <i slot="suffix" class="el-input__icon el-icon-search" @click="handleSelectMaterial(scope.row,scope.$index)"></i>
                      </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="数量" prop="operNumber" width="60" align="center">
                  <template slot-scope="scope">
                    <el-form-item  :prop="'znDepotItemList.' + scope.$index + '.operNumber'" :rules="rules.operNumber" style="margin-bottom: 0px; ">
                      <el-input-number size="small" style="width: 100%;" :min="0" :controls="false" v-model="scope.row.operNumber" @change="changeUnitPrice(scope.row,scope.$index)"></el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="单价" prop="unitPrice" width="60" align="center">
                  <template slot-scope="scope">
                    <el-form-item  :prop="'znDepotItemList.' + scope.$index + '.unitPrice'" :rules="rules.unitPrice" style="margin-bottom: 0px; ">
                       <el-input-number :precision="2" size="small" style="width: 100%;" :min="0" :controls="false" v-model="scope.row.unitPrice" @change="changeUnitPrice(scope.row,scope.$index)"></el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <!-- <el-table-column label="含税单价" prop="taxUnitPrice">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.taxUnitPrice" placeholder="请输入含税单价" />
                  </template>
                </el-table-column> -->
                <el-table-column label="金额" prop="allPrice" width="80" align="center">
                  <template slot-scope="scope">
                    <el-form-item  :prop="'znDepotItemList.' + scope.$index + '.allPrice'" :rules="rules.allPrice" style="margin-bottom: 0px; ">
                      <el-input-number :precision="2" size="small" style="width: 100%;" :min="0" :controls="false" v-model="scope.row.allPrice" @change="changeAllPrice(scope.row,scope.$index)"></el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="税率" prop="taxRate" width="60" align="center">
                  <template slot-scope="scope">
                    <el-input-number placeholder="%" size="small" style="width: 100%;" :min="0" :max="100" :controls="false" v-model="scope.row.taxRate" @change="calRate(scope.row,scope.$index)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="税额" prop="taxMoney" width="60" align="center">
                  <template slot-scope="scope">
                    <el-input-number :precision="2" size="small" style="width: 100%;" :min="0" :controls="false" v-model="scope.row.taxMoney" disabled></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="价税合计" prop="taxLastMoney" width="90" align="center">
                  <template slot-scope="scope">
                    <el-input-number :precision="2" size="small" style="width: 100%;" :min="0" :controls="false" v-model="scope.row.taxLastMoney" disabled></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="备注" prop="remark" width="80" align="center">
                  <template slot-scope="scope">
                    <el-input size="small" v-model="scope.row.remark" />
                  </template>
                </el-table-column>
              </el-table>

            <el-row style="top: 0.625rem;">
              <el-form-item label="" prop="remark" label-width="0px">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
              </el-form-item>
            </el-row>
            <el-row style="top: 0.625rem;">
              <el-col :span="6">
                <el-form-item label="优惠率" prop="discount" label-width="100px">
                   <el-input v-model="form.discount" type="number" @input="discountTotal(0)">
                      <template slot="append">%</template>
                    </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="付款优惠" prop="discountMoney" label-width="100px">
                   <el-input v-model="form.discountMoney" type="number" @input="discountTotal(1)" >
                    </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="优惠后金额" prop="discountLastMoney" label-width="100px">
                  <el-input-number :precision="2" size="small" style="width: 100%;" :min="0" :controls="false" v-model="form.discountLastMoney" disabled></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="6">
              </el-col>
            </el-row>
            <el-row>
              <el-form-item label="附件名称" prop="fileName" label-width="100px">
                <fileUpload v-model="form.fileName" :fileType="['png', 'jpg', 'jpeg','xls','doc','pdf']"/>
              </el-form-item>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 选择商品对话框 -->
    <el-dialog :title="material.title" :visible.sync="material.open" width="1200px" append-to-body>
      <el-form :model="material.queryParams" ref="materialQueryForm" :inline="true" label-width="68px">
          <el-form-item label="商品" prop="name">
              <el-input v-model="material.queryParams.params.name" placeholder="条码、名称、规格、型号" clearable size="small" />
            </el-form-item>
          <el-form-item label="类别" prop="categoryId" >
              <treeselect v-model="material.queryParams.categoryId"  style="width: 13.25rem;" :options="material.materialcategoryOptions" :show-count="true" placeholder="请选择类别" />
          </el-form-item>
          <el-form-item label="仓库" prop="depotId">
            <el-select
              v-model="material.queryParams.depotId"
              placeholder="请选择仓库"
              clearable
              size="small"
            >
              <el-option
                v-for="depot in depots"
                :key="depot.id"
                :label="depot.name"
                :value="depot.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="small" @click="handleMaterialQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="small" @click="resetMaterialQuery">重置</el-button>
          </el-form-item>
      </el-form>
      <el-table v-loading="material.loading" :data="material.materialList"  @selection-change="handleMaterialSelectionChange" @row-dblclick="doDbClickMaterial">
            <el-table-column type="selection" width="55"  />
            <!-- <el-table-column label="ID" align="center" prop="id" /> -->
            <el-table-column label="条码" align="center" prop="barCode" />
            <el-table-column label="名称" align="center" prop="name"/>
            <el-table-column label="类别" align="center" prop="categoryName" />
            <el-table-column label="规格" align="center" prop="standard" />
            <el-table-column label="型号" align="center" prop="model" />
            <el-table-column label="颜色" align="center" prop="color" />
            <el-table-column label="库存" align="center" prop="currentNumber" />
            <el-table-column label="单位" align="center" prop="unit" width="60" />
            <el-table-column label="多属性" align="center" prop="sku" />
            <el-table-column label="扩展信息" align="center" prop="mfrs" />
            <el-table-column label="序列号" align="center"  prop="enableSerialNumber" width="60" >
              <template slot-scope="scope">
                 <el-tag v-if="scope.row.enableSerialNumber==0" type="danger">无</el-tag>
                 <el-tag v-if="scope.row.enableSerialNumber==1" >有</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="批号" align="center" prop="enableBatchNumber"  width="55" >
              <template slot-scope="scope">
                 <el-tag v-if="scope.row.enableBatchNumber==0" type="danger">无</el-tag>
                 <el-tag v-if="scope.row.enableBatchNumber==1" >有</el-tag>
                </template>
              </el-table-column>
          </el-table>

          <pagination v-show="material.total>0" :total="material.total" :page.sync="material.queryParams.pageNum" :limit.sync="material.queryParams.pageSize"
            @pagination="getMaterialList" />

            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitMaterialForm">确 定</el-button>
              <el-button @click="cancelMaterial">取 消</el-button>
            </div>
    </el-dialog>

    <!-- 添加会员信息对话框 -->
    <el-dialog :title="member.title" :visible.sync="member.open" width="800px" append-to-body>
      <el-form ref="memberForm" :model="member.form" :rules="member.rules" label-width="110px">
        <el-row>
            <el-col :span="12">
              <el-form-item label="名称" prop="supplier">
                <el-input v-model="member.form.supplier" placeholder="请输入名称" />
              </el-form-item>
            </el-col >
            <el-col :span="12">
             <el-form-item label="联系人" prop="contacts">
               <el-input v-model="member.form.contacts" placeholder="请输入联系人" />
             </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="telephone">
                <el-input v-model="member.form.telephone" placeholder="请输入手机号码" />
              </el-form-item> 
            </el-col >
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phoneNum">
                <el-input v-model="member.form.phoneNum" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
                <el-form-item label="电子邮箱" prop="email">
                  <el-input v-model="member.form.email" placeholder="请输入电子邮箱" />
                </el-form-item>
            </el-col >
            <el-col :span="12">
                <el-form-item label="传真" prop="fax">
                  <el-input v-model="member.form.fax" placeholder="请输入传真" />
                </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="期初应收" prop="beginNeedGet">
                <el-input v-model="member.form.beginNeedGet" placeholder="请输入期初应收" />
              </el-form-item>
            </el-col >
            <el-col :span="12">
              <el-form-item label="期初应付" prop="beginNeedPay">
                <el-input v-model="member.form.beginNeedPay" placeholder="请输入期初应付" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="纳税人识别号" prop="taxNum">
                <el-input v-model="member.form.taxNum" placeholder="请输入纳税人识别号" />
              </el-form-item>
            </el-col >
            <el-col :span="12">
              <el-form-item label="税率" prop="taxRate">
                <el-input v-model="member.form.taxRate" placeholder="请输入税率" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="开户行" prop="bankName">
                <el-input v-model="member.form.bankName" placeholder="请输入开户行" />
              </el-form-item>
            </el-col >
            <el-col :span="12">
              <el-form-item label="账号" prop="accountNumber">
                <el-input v-model="member.form.accountNumber" placeholder="请输入账号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="地址" prop="address">
                <el-input v-model="member.form.address" placeholder="请输入地址" />
              </el-form-item>
            </el-col >
            <el-col :span="12">
              <el-form-item label="备注" prop="description">
                <el-input v-model="member.form.description" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMemberForm">确 定</el-button>
        <el-button @click="cancelMember">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改结算账号对话框 -->
    <el-dialog :title="account.title" :visible.sync="account.open" width="600px" append-to-body>
      <el-form ref="accountForm" :model="account.form" :rules="account.rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="account.form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="编号" prop="serialNo">
          <el-input v-model="account.form.serialNo" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="期初金额" prop="initialAmount">
          <el-input v-model="account.form.initialAmount" placeholder="请输入期初金额" />
        </el-form-item>
        <el-form-item label="当前余额" prop="currentAmount">
          <el-input v-model="account.form.currentAmount" placeholder="请输入当前余额" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="account.form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAccountForm">确 定</el-button>
        <el-button @click="cancelAccount">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 单据导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body :close-on-click-modal="false">
       <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag

      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size:12px" @click="exportTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅支持导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="upload.isUploading" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <bill-detail ref="billDetail"></bill-detail>
  </div>
</template>

<script>
import { listRetail, getRetail, delRetail, addRetail, updateRetail, getBillNo, updateRetailStatus } from "@/api/bill/retail";
import { addSupplier } from "@/api/basicsystem/supplier";
import { addAccount } from "@/api/basicsystem/account";
import { addDepot } from "@/api/basicsystem/depot";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { materialcategorytreeselect } from "@/api/material/materialcategory";
import {parseTime} from "@/utils/ruoyi";
import Sortable from 'sortablejs';
import { listMaterialSelect } from "@/api/material/material";
import BillDetail from '../../report/comm/dialog/BillDetail'
import { findBillDetailByNumber } from "@/api/bill/retail";
import Vue from 'vue';
import * as math from 'mathjs';
import { getToken } from "@/utils/auth";
export default {
  name: "Retail",
  dicts: ['depot_head_status'],
  components: { Treeselect, BillDetail },
  data() {
    return {
      // 搜索栏 展开/收起 按钮
      toggleSearchStatus:false,
      // 遮罩层
      loading: true,
      submitLoading:false,
      // 选中数组
      ids: [],
      // 选中可删除数组
      deleteIds:[],
      // // 审核需要选中数组
      // checkIds: [],
      // // 反审核需要选中数组
      // disCheckIds: [],
      // 子表选中数据
      checkedZnDepotItem: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单据管理表格数据
      retailList: [],
      // 单据子表格数据
      znDepotItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: '其它',
        subType: '采购订单',
        defaultNumber: null,
        number: null,
        operTimeRange:[],
        operTime: null,
        organId: null,
        creator: null,
        accountId: null,
        changeAmount: null,
        backAmount: null,
        totalPrice: null,
        payType: null,
        billType: null,
        fileName: null,
        salesMan: null,
        accountIdList: null,
        accountMoneyList: null,
        discount: null,
        discountMoney: null,
        discountLastMoney: null,
        otherMoney: null,
        status: null,
        linkNumber: null,
        tenantId: null,
        deleteFlag: null,
        //商品信息
        material:null,
        params:{
          beginOperTime:null,
          endOperTime:null
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        organId:[
          { required: true, message: "供应商不能为空", trigger: "blur" },
        ],
        operTime:[
          {required: true, message: '单据日期不能为空', trigger: 'blur' }
        ],
        // changeAmount:[
        //   {required: true, message: '请输入收款金额', trigger: 'blur' }
        // ],
        // accountId:[
        //   {required: true, message: '请选择收款账户', trigger: 'blur' }
        // ],
        allPrice:[
          {required: true, message: '金额不能为空', trigger: 'blur' },
        ],
        unitPrice:[
          {required: true, message: '单价不能为空', trigger: 'blur' },
        ],
        operNumber:[
          {required: true, message: '数量不能为空', trigger: 'blur' },
        ],
      },
      //会员下拉框数据
      members:[],
      //操作员下拉框数据
      users:[],
      //账户下拉框数据
      accounts:[],
      //默认账户
      defaultAcount:null,
      isModel:false,
      isColor:false,
      isMfrs:false,
      isSerialNumber:false,
      isSku:false,
      isTableOut:true,//是否商品列表内修改，
      //选择商品窗口
      material:{
        // 弹出层标题
        title: "选择商品",
        // 是否显示弹出层
        open: false,
        //加载
        loading:false,
        // 总条数
        total: 0,
        //商品数据
        materialList:[],
        //选中商品数据
        materials:[],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          categoryId:null,
          depotId:null,
          params:{
            name:null,
            materialExtentIds:[],
          }
        },
        //类型树
        materialcategoryOptions:[],
        //当前选择商品的行号
        currentSelectRowNumber:0,
      },
      //新增会员窗口
      member:{
        // 弹出层标题
        title: "新增供应商",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          supplier: [
            { required: true, message: "名称不能为空", trigger: "blur" }
          ],
        },
      },
      //新增账户窗口
      account:{
        // 弹出层标题
        title: "新增账户",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
         name :[
           { required: true, message: "名称不能为空", trigger: "blur" }
         ],
         serialNo :[
           { required: true, message: "编码不能为空", trigger: "blur" }
         ],
        },
      },
      //仓库下拉框数据
      depots:[],
      //仓库操作
      depot:{
        // 弹出层标题
        title: "",
        //0 批量设置仓库  1新增仓库
        type :0,
        // 是否显示弹出层
        open: false,
        // 非多个禁用
        multiple: true,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          id: [
            { required: true, message: "仓库名称不能为空", trigger: "blur" }
          ],
          name: [
            { required: true, message: "名称不能为空", trigger: "blur" }
          ],
        }
      },
      // 单据内容导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        title:"单据导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/bill/retail/importMaterialData",
      },
    }
  },
  watch:{
    "form.totalPrice":function(n,o){
        this.form.discountMoney = math.format(math.round(math.chain(math.bignumber(this.form.totalPrice)).add(math.bignumber(this.form.otherMoney)).multiply(math.bignumber(this.form.discount)).multiply(0.01).done(),2));
    },
  },
  beforeCreate() {
    this.getSuppliers({'type':'供应商'}).then(response => {
      this.members = response.data;
    });
    this.getUsers().then(response => {
      this.users =  response.data;
    });
  },
  created() {
    this.getList();
  },
  mounted() {
    this.materialcategorytreeselect();
    this.getAccounts().then(response =>{
      this.accounts =  response.data;
      this.defaultAcount = this.accounts.find(item => item.isDefault==1)
    });
    this.getDepots().then(response =>{
      this.depots =  response.data;
    });
  },
  methods: {
    //根据单据查询详情
    myHandleDetail(row){
        let that = this
        //this.toFromType = row.fromType;
           let queryParm={ number: row.number }
           findBillDetailByNumber(queryParm).then(response => {
             console.log(response.data)
             //this.liushuiList = response.data;
             that.$refs.billDetail.show(response.data,row.subType);
             that.$refs.billDetail.title=response.data.subType+"-详情";
           });
    },
    // //会员id转为名称
    organFormat(row, column) {
      var actions = [];
      this.members.filter(item => {
      	if (item.id == row.organId) {
      		actions.push(item.supplier);
      	}
      })
      return actions.join('');
    },
    //操作员id转为名称
    creatorFormat(row, column) {
      var actions = [];
      this.users.filter(item => {
      	if (item.userId == row.creator) {
      		actions.push(item.nickName);
      	}
      })
      return actions.join('');
    },
    /** 查询单据管理列表 */
    getList() {
      this.loading = true;
      if(this.queryParams.operTimeRange !=null && this.queryParams.operTimeRange.length>0){
        this.queryParams.params.beginOperTime = this.queryParams.operTimeRange[0];
        this.queryParams.params.endOperTime = this.queryParams.operTimeRange[1]
      }else{
        this.queryParams.params.beginOperTime = null;
        this.queryParams.params.endOperTime = null
      }
      listRetail(this.queryParams).then(response => {
        this.retailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: '其它',
        subType: '采购订单',
        defaultNumber: null,
        number: null,
        createTime: null,
        operTime: null,
        organId: null,
        creator: null,
        accountId: null,
        changeAmount: 0,
        backAmount: 0,
        totalPrice: 0,
        payType: null,
        billType: null,
        remark: null,
        fileName: null,
        salesMan: null,
        accountIdList: null,
        accountMoneyList: null,
        discount: null,
        discountMoney: null,
        discountLastMoney: null,
        otherMoney: null,
        status: "0",
        linkNumber: null,
        tenantId: null,
        deleteFlag: null,
        znDepotItemList:[]
      };
      this.resetForm("form");
      this.submitLoading = false;
	  // this.handleAddZnDepotItem();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      let temps =[];
      temps = selection.filter(item => {
          return item.status =='0';
      })
      this.deleteIds = temps.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isModel = false;
      this.isColor = false;
      this.isMfrs = false;
      this.isSerialNumber = false;
      if(this.defaultAcount){
        this.form.accountId= this.defaultAcount.id;
      }
      this.open = true;
      this.form.discount = 0;
      this.form.discountMoney = 0;
      this.form.discountLastMoney = 0;
      this.title = "新增";
      getBillNo('CGDD').then(response =>{
         this.form.defaultNumber = response.data;
      });
      this.form.operTime =  parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
      this.$nextTick(()=>{
              //此时能够调到ref，而且table也正常刷新了
            const el = this.$refs.znDepotItem.$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0];
            const that = this;
            const sortable = Sortable.create(el, {
                  handle: ".allowDrag",
                  onEnd: evt => {
                    const targetRow = this.form.znDepotItemList.splice(evt.oldIndex, 1)[0];
                    this.form.znDepotItemList.splice(evt.newIndex, 0, targetRow);
                    for (let index in this.form.znDepotItemList) {
                      this.form.znDepotItemList[index].sort = parseInt(index) + 1;
                    }
                    // console.log(this.form.znDepotItemList)
                  }
                });
          });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isTableOut = false;
      const id = row.id || this.ids
      this.form.operTime =  parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
      getRetail(id).then(response => {
        this.form = response.data;
        this.form.znDepotItemList = response.data.znDepotItemList;
        this.open = true;
        this.title = "修改单据管理";
      });
    },
    /** 复制按钮操作 */
    handleCopy(row){
      this.reset();
      const id = row.id;
      getRetail(id).then(response => {
        this.form = response.data;
        this.form.id = null;
        this.form.znDepotItemList = response.data.znDepotItemList;
        getBillNo('CGDD').then(response =>{
           this.form.defaultNumber = response.data;
        });
        this.open = true;
        this.title = "复制新增";
      });
    },
     /** 转按钮操作 */
    handleCopyAdd(row){

    },
    /** 提交按钮 */
    submitForm() {
      this.submitLoading = true;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.znDepotItemList.length==0){
            this.$modal.msgError("单据明细不能为空");
            this.submitLoading = false;
          }else{
            let that =  this;
            let errorList1 = this.form.znDepotItemList.filter(item => item.materialId ==null);
            if(errorList1.length>0){
                this.$modal.msgError("单据明细中(产品)有误，请选择系统中产品重新提交");
                this.submitLoading = false;
            }else{
              let errorList = this.form.znDepotItemList.filter(item => math.format(math.round(math.chain(math.bignumber(item.unitPrice)).multiply(math.bignumber(item.operNumber)).done(),2))  != math.format(math.round(math.bignumber(item.allPrice),2)) );
              if(errorList.length>0){
                 let materialNames = errorList.map(item=>{return item.materialName});
                 this.$modal.msgError("单据明细中（数量、单价、金额）有误的产品：("+materialNames.join(",")+")，请纠正后重新提交");
                 this.submitLoading = false;
              }else{
                 if (this.form.id != null) {
                   updateRetail(this.form).then(response => {
                     this.$modal.msgSuccess("修改成功");
                     this.open = false;
                     this.getList();
                   });
                 } else {
                   // if(this.form.changeAmount ==0){
                   //   this.$modal.msgError("请先输入收款金额");
                   // }else{
                     addRetail(this.form).then(response => {
                       this.$modal.msgSuccess("新增成功");
                       this.open = false;
                       this.getList();
                     });
                   // }
                 }
              }
            }
          }
        }else{
          this.submitLoading = false;
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if((row.status ==undefined && this.deleteIds.length==0) || (row.status !=undefined &&  row.status !='0')){
        this.$modal.msgError("只能删除未审核单据！");
      }else{
        const ids = row.id || this.deleteIds;
        this.$modal.confirm('是否确认删除单据管理编号为"' + ids + '"的数据项？').then(function() {
          return delRetail(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    },
	/** 单据子序号 */
    rowZnDepotItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 单据子添加按钮操作 */
    handleAddZnDepotItem() {
      let obj = {};
      //barCode materialId materialName standard model color currentNumber materialUnit sku operNumber unitPrice allPrice remark
      obj.depotId = null;
      obj.materialId = null;
      obj.materialExtendId = null;
      obj.materialUnit = null;
      obj.materialName = null;
      obj.barCode = null;
      obj.standard = null;
      obj.model = null;
      obj.materialName = null;
      obj.color = null;
      obj.currentNumber = null;
      obj.sku = null;
      obj.operNumber = null;
      obj.basicNumber = null;
      obj.unitPrice = null;
      obj.taxUnitPrice = null;
      obj.allPrice = null;
      obj.remark = null;
      // obj.depotId = this.defaultDepot.id;
      obj.anotherDepotId = null;
      obj.taxRate = null;
      obj.taxMoney = null;
      obj.taxLastMoney = null;
      obj.materialType = null;
      obj.snList = null;
      obj.batchNumber = null;
      obj.expirationDate = null;
      obj.tenantId = null;
      obj.deleteFlag = null;
      obj.unitRatio = 1;
      this.form.znDepotItemList.push(obj);
    },
    /** 单据子删除按钮操作 */
    handleDeleteZnDepotItem() {
      if (this.checkedZnDepotItem.length == 0) {
        this.$modal.msgError("请先选择要删除的单据子数据");
      } else {
		this.isTableOut =true;
        const znDepotItemList = this.form.znDepotItemList;
        const checkedZnDepotItem = this.checkedZnDepotItem;
        this.form.znDepotItemList = znDepotItemList.filter(function(item) {
          return checkedZnDepotItem.indexOf(item.index) == -1
        });
      }
    },
   /** 导入按钮操作 */
   handleImport() {
     this.upload.title = "单据商品导入";
     this.upload.open = true;
   },
   /** 下载模板操作 */
   exportTemplate() {
         this.download('bill/retail/exportTemplate', {
           ...this.material.exportQueryParams
         }, `订单商品导入模板_${new Date().getTime()}.xlsx`)
   },
   // 文件上传中处理
   handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
   },
   // 文件上传成功处理
   handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        console.log(response)
        this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        if(response.code =='200' && response.data.length>0){
           this.isTableOut =true;
           let that = this
           response.data.forEach((item,index) =>{
             let isFlag = false;
             let oldList = that.form.znDepotItemList.forEach((item1,index1) =>{
               // console.log(item1)
                 if(item1.materialId == item.id && item1.materialExtendId == item.materialExtendId && !isFlag){
                   item1.operNumber  = item1.operNumber + item.operNumber;
                   item1.basicNumber = math.format(math.add(math.bignumber(item1.basicNumber),math.round(math.multiply(math.bignumber(item.operNumber),math.bignumber(item.unitRatio)),2)));
                   item1.allPrice = math.format(math.round(math.multiply(math.bignumber(item1.operNumber),math.bignumber(item1.unitPrice)),2));
                   item1.taxMoney = math.format(math.round(math.multiply(math.bignumber(item1.allPrice),math.bignumber(item1.taxRate)),2));
                   item1.taxLastMoney = math.format(math.round(math.multiply(math.bignumber(item1.operNumber),math.bignumber(item1.unitPrice)),2));
                   item1.remark = item.remak;
                   isFlag =  true;
                   return;
                 }
             });
             if(!isFlag){
              let obj1 = {};
              let depotId = item.depotId || that.material.queryParams.depotId;
              obj1.depotId = depotId ;
              obj1.barCode = item.barCode;
              obj1.materialId = item.id;
              obj1.materialExtendId = item.materialExtendId;
              obj1.materialName = item.name;
              obj1.materialUnit = item.unit;
              obj1.sku =  item.sku;
              obj1.allPrice = math.format(math.round(math.multiply(math.bignumber(item.operNumber),math.bignumber(item.purchaseDecimal)),2));
              obj1.unitPrice = item.purchaseDecimal;
              obj1.materialType = item.categoryId;
              obj1.currentNumber = item.currentNumber;
              obj1.materialSerialNumber = item.serialNumber;
              obj1.color = item.color;
              obj1.model = item.model;
              obj1.standard = item.standard;
              obj1.unitRatio = item.unitRatio;
              obj1.operNumber = item.operNumber;
              // obj1.basicNumber = item.operNumber*item.unitRatio;
              obj1.basicNumber = math.format(math.round(math.multiply(math.bignumber(obj1.operNumber),math.bignumber(item.unitRatio)),2));
              obj1.taxRate = 0;
              obj1.taxMoney = 0;
              obj1.taxLastMoney = math.format(math.round(math.multiply(math.bignumber(item.operNumber),math.bignumber(item.purchaseDecimal)),2));
              obj1.remark = item.remark;
              that.form.znDepotItemList.push(obj1);
             that.isModel = !that.isModel?item.model !=null && item.model !='':that.isModel;
             that.isColor = !that.isColor?item.color !=null && item.color !='':that.isColor;
             that.isMfrs = !that.isMfrs?item.mfrs !=null && item.mfrs !='':that.isMfrs;
             that.isSerialNumber = !that.isSerialNumber?item.serialNumber !=null && item.serialNumber !='':that.isSerialNumber;
             }
          })
        }
   },
   // 提交上传文件
   submitFileForm() {
       this.$refs.upload.submit();
   },
    /** 复选框选中数据 */
    handleZnDepotItemSelectionChange(selection) {
      this.checkedZnDepotItem = selection.map(item => item.index)
      this.depot.multiple = !selection.length
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bill/retail/export', {
        ...this.queryParams
      }, `retail_${new Date().getTime()}.xlsx`)
    },
     /** 搜索栏展开/收起按钮操作 */
    handleToggleSearch(){
      this.toggleSearchStatus = !this.toggleSearchStatus;
    },
    /** 批量操作按钮操作 */
    handleCommand(command) {
      if(command == 'delete'){
        // this.$message('click on item ' + command);
        this.handleDelete(this);
      }else if(command == 'enabled'){
         this.handleStatus(1);
        // this.$message('click on item ' + command);
      }else if(command == 'disabled'){
        this.handleStatus(0);
        // this.$message('click on item ' + command);
      }else if(command == 'batchSetDepot'){
        this.handleDepot(0);
      }else if(command == 'goAddDepot'){
        this.handleDepot(1);
      }
    },
    /** 审核、反审核按钮操作 */
    handleStatus(status) {
      const statusTxt = status == 1 ? "审核":"反审核";
      const ids = this.ids;
      this.$modal.confirm('是否确认'+statusTxt+' 编号为"' + ids + '"的单据？').then(function() {
        return updateRetailStatus(ids,status);
      }).then((res) => {
      		this.getList();
      		if(res.code == 200){
      			this.$modal.msgSuccess(res.msg);
      		}else{
      			this.$modal.msgError(res.msg);
      		}
      }).catch(() => {});
    },
    //条码搜索框，打开商品选择框
    handleSelectMaterial(row,index){
      // console.log(row)
      this.material.materials=[];
      this.material.currentSelectRowNumber = index;
      this.material.queryParams.depotId = row.depotId;
      this.material.queryParams.params.name = row.barCode;
	  let materials =  this.form.znDepotItemList.filter((item,index)=>{ return item.materialExtendId !=null});
	  let materialExtentIds =  materials.map(item => item.materialExtendId);
	  if(materialExtentIds.length>0){
	     this.material.queryParams.params.materialExtentIds = materialExtentIds;
	  }
      this.getMaterialList();
      this.material.open = true;
    },
    //双击选中商品 选中事件
    doDbClickMaterial(row){
      let obj = this.form.znDepotItemList[this.material.currentSelectRowNumber];
      obj.barCode = row.barCode;
      obj.materialId = row.id;
      obj.materialExtendId = row.materialExtendId;
      obj.materialName = row.name;
      obj.materialUnit = row.unit;
      obj.sku =  row.sku;
      obj.allPrice = row.commodityDecimal;
      obj.unitPrice = row.commodityDecimal;
      obj.currentNumber = row.currentNumber;
      obj.materialType = row.categoryId;
      obj.materialSerialNumber = row.serialNumber;
      obj.color = row.color;
      obj.model = row.model;
      obj.standard = row.standard;
      obj.unitRatio = row.unitRatio;
      obj.operNumber = 1;
      obj.basicNumber = row.unitRatio;
      this.isModel = !this.isModel?row.model !=null && row.model !='':this.isModel;
      this.isColor = !this.isColor?row.color !=null && row.color !='':this.isColor;
      this.isMfrs = !this.isMfrs?row.mfrs !=null && row.mfrs !='':this.isMfrs;
      this.isSerialNumber = !this.isSerialNumber?row.serialNumber !=null && row.serialNumber !='':this.isSerialNumber;
      // this.form.znDepotItemList[this.material.currentSelectRowNumber] = obj;
       this.material.open =  false;
    },
	//选择商品 对话框中，选中事件
    handleMaterialSelectionChange(selection){
      this.material.materials = selection.map(item => item)
      // this.material.ids = selection.map(item => item.id)
      this.material.single = selection.length!==1
      this.material.multiple = !selection.length
    },
    /** 查询类型下拉树结构 */
    materialcategorytreeselect() {
      materialcategorytreeselect().then(response => {
        this.material.materialcategoryOptions = response.data;
      });
    },
    /** 查询产品列表 */
    getMaterialList() {
      this.material.loading = true;
      listMaterialSelect(this.material.queryParams).then(response => {
        // console.log(response)
        this.material.materialList = response.rows;
        this.material.total = response.total;
        this.material.loading = false;
      });
    },
    /** 商品搜索按钮操作 */
    handleMaterialQuery() {
      this.material.queryParams.pageNum = 1;
       this.getMaterialList();
    },
    /** 商品搜索重置按钮操作 */
    resetMaterialQuery() {
      this.resetForm("materialQueryForm");
      this.handleMaterialQuery();
    },
    submitMaterialForm(){
        if(this.material.materials.length > 0){
          this.isTableOut = true;
          let obj = this.form.znDepotItemList[this.material.currentSelectRowNumber];
          let goods = this.material.materials[0];
          // barCode materialId materialName standard model color currentNumber materialUnit sku operNumber unitPrice allPrice remark
          obj.barCode = goods.barCode;
          obj.materialId = goods.id;
          obj.materialExtendId = goods.materialExtendId;
          obj.materialName = goods.name;
          obj.materialUnit = goods.unit;
          obj.sku =  goods.sku;
          obj.allPrice = goods.purchaseDecimal;
          obj.unitPrice = goods.purchaseDecimal;
          obj.currentNumber = goods.currentNumber;
          obj.materialType = goods.categoryId;
          obj.materialSerialNumber = goods.serialNumber;
          obj.color = goods.color;
          obj.model = goods.model;
          obj.standard = goods.standard;
          obj.unitRatio = goods.unitRatio;
          obj.operNumber = 1;
          obj.basicNumber = goods.unitRatio;
          obj.taxLastMoney = goods.purchaseDecimal;
          obj.taxRate = 0;
          obj.taxMoney = 0;
          // console.log(goods)
          // console.log(obj)
          this.isModel = !this.isModel?goods.model !=null && goods.model !='':this.isModel;
          this.isColor = !this.isColor?goods.color !=null && goods.color !='':this.isColor;
          this.isMfrs = !this.isMfrs?goods.mfrs !=null && goods.mfrs !='':this.isMfrs;
          this.isSerialNumber = !this.isSerialNumber?goods.serialNumber !=null && goods.serialNumber !='':this.isSerialNumber;
          this.form.znDepotItemList[this.material.currentSelectRowNumber] = obj;
          if( this.material.materials.length>1){
            let that = this;
            this.material.materials.forEach((item,index) =>{
              if(index>=1){
                let obj1 = {};
                let depotId = item.depotId || that.material.queryParams.depotId;
                obj1.depotId = depotId ;
                obj1.barCode = item.barCode;
                obj1.materialId = item.id;
                obj1.materialExtendId = item.materialExtendId;
                obj1.materialName = item.name;
                obj1.materialUnit = item.unit;
                obj1.sku =  item.sku;
                obj1.allPrice = item.purchaseDecimal;
                obj1.unitPrice = item.purchaseDecimal;
                obj1.materialType = item.categoryId;
                obj1.currentNumber = item.currentNumber;
                obj1.materialSerialNumber = item.serialNumber;
                obj1.color = item.color;
                obj1.model = item.model;
                obj1.standard = item.standard;
                obj1.unitRatio = item.unitRatio;
                obj1.operNumber = 1;
                obj1.basicNumber = item.unitRatio;
                obj1.taxRate = 0;
                obj1.taxMoney = 0;
                obj1.taxLastMoney = item.purchaseDecimal;
                that.form.znDepotItemList.push(obj1);
               that.isModel = !that.isModel?item.model !=null && item.model !='':that.isModel;
               that.isColor = !that.isColor?item.color !=null && item.color !='':that.isColor;
               that.isMfrs = !that.isMfrs?item.mfrs !=null && item.mfrs !='':that.isMfrs;
               that.isSerialNumber = !that.isSerialNumber?item.serialNumber !=null && item.serialNumber !='':that.isSerialNumber;
              }
            })
          }
          this.material.open =  false;
        }
      // console.log(this.form.znDepotItemList)
    },
    cancelMaterial(){
       this.material.open =  false;
       this.material.materialList =[];
    },
    visibleChange(visible, refName, onClick, btnName) {
        if (visible) {
          const ref = this.$refs[refName]
          let popper = ref.$refs.popper
          if (popper.$el) popper = popper.$el
          if (!Array.from(popper.children).some(v => v.className === 'el-template-menu__list')) {
              const el = document.createElement('ul')
              el.className = 'el-template-menu__list'
              el.style = 'border-top:2px solid rgb(219 225 241); font-size: 14px;margin-top: 0px;margin-bottom: 3px;'
              el.innerHTML = `<li class="el-cascader-node el-select-dropdown__item" style="margin-left: -40px;height:37px;line-height: 50px">
                      <span class="el-cascader-node__label" style="margin-left: -13px ;"><i class="font-blue el-icon-plus" style="padding-right: 3px;"></i>`+btnName+`</span>
                      </li>`
              popper.appendChild(el)
              el.onclick = () => {
                // 底部按钮的点击事件 点击后想触发的逻辑也可以直接写在这
                onClick && onClick()
                if (ref.toggleDropDownVisible) {
                     ref.toggleDropDownVisible(false)
                } else {
                     ref.visible = false
                }
              }
          }
        }
    },
    /**
     * 点击添加会员
     */
    addOrganClick(){
      this.resetMember();
      this.member.open =  true;
    },
    /** 新增会员提交按钮 */
    submitMemberForm() {
      this.$refs["memberForm"].validate(valid => {
        if (valid) {
            addSupplier(this.member.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.member.open = false;
              this.getSuppliers({'type':'供应商'}).then(response => {
               this.members = response.data;
             });
            });
        }
      });
    },

    cancelMember(){
      this.member.open = false;
    },
    // 新增会员表单重置
    resetMember() {
      this.member.form = {
        id: null,
        supplier: null,
        contacts: null,
        telephone: null,
        phoneNum: null,
        email: null,
        fax: null,
        beginNeedGet: null,
        beginNeedPay: null,
        taxNum: null,
        taxRate: null,
        bankName: null,
        accountNumber: null,
        address: null,
        description: null,
        isystem: null,
        type: '供应商',
        enabled: 1,
        advanceIn: null,
        allNeedGet: null,
        allNeedPay: null,
        tenantId: null,
        deleteFlag: null
      };
      this.resetForm("memberForm");
    },
    /**
     * 点击添加账户
     */
    addAccountClick(){
      this.resetAccount();
      this.account.open =  true;
    },
    /** 新增账户提交按钮 */
    submitAccountForm() {
      this.$refs["accountForm"].validate(valid => {
        if (valid) {
            addAccount(this.account.form).then(response => {
              this.$modal.msgSuccess("账户新增成功");
              this.account.open = false;
              this.getAccounts().then(response => {
               this.accounts = response.data;
             });
            });
        }
      });
    },
    cancelAccount(){
      this.account.open = false;
      this.resetAccount();
    },
    // 表单重置
    resetAccount() {
      this.account.form = {
        id: null,
        name: null,
        serialNo: null,
        initialAmount: null,
        currentAmount: null,
        remark: null,
        isDefault: null,
        tenantId: null,
        deleteFlag: null
      };
      this.resetForm("accountForm");
    },
    //新增页面 商品列表合计
    getItemSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        const that = this;
        columns.forEach((column, index) => {
          if(column.property =='operNumber' || column.property =='taxMoney' || column.property =='allPrice' || column.property =='taxLastMoney' ){
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return math.add(math.bignumber(prev),math.bignumber(curr));
                } else {
                  return math.bignumber(prev);
                }
              }, 0);
            }
            if(column.property =='operNumber'){
              sums[index]= (sums[index] !=undefined && sums[index] !=null ?parseFloat(sums[index]):0);
            }
            if(column.property =='taxMoney'){
              sums[index]= (sums[index] !=undefined && sums[index] !=null ?parseFloat(sums[index]):0);
            }
            if(column.property =='allPrice'){
              sums[index]= (sums[index] !=undefined && sums[index] !=null ?parseFloat(sums[index]):0);
            }
            if(column.property =='taxLastMoney'){
             sums[index]= (sums[index] !=undefined && sums[index] !=null ?parseFloat(sums[index]):0);
             if(that.isTableOut){//是否为表格内修改
                that.form.totalPrice = sums[index];
                that.form.debt = 0;
                that.form.discountLastMoney = math.format(math.subtract(math.bignumber(sums[index]),math.bignumber(that.form.discountMoney)));
                that.form.changeAmount = math.format(math.chain(math.bignumber(that.form.discountLastMoney)).add(math.bignumber(that.form.otherMoney)).subtract(math.bignumber(that.form.debt)).done());
                that.isTableOut = false;
             }
            }
              sums[index];
               return;
          }else{
            sums[index] = '';
             return;
          }
        });
        return sums;
      },
      //修改商品金额
      changeAllPrice(row,index){
        this.isTableOut = true;
        row.unitPrice = math.format(math.round(math.chain(math.bignumber(row.allPrice)).divide(math.bignumber(row.operNumber)).done(),2));
        row.taxMoney = math.format(math.round(math.multiply(math.bignumber(row.allPrice),math.bignumber(row.taxRate),math.bignumber(0.01)),2));
        row.taxLastMoney = math.format(math.add(math.bignumber(row.taxMoney),math.bignumber(row.allPrice)));
      },
      //修改商品单价、数量
      changeUnitPrice(row,index){
          this.isTableOut = true;
          let allPrice = math.format(math.round(math.multiply(math.bignumber(row.unitPrice),math.bignumber(row.operNumber)),2));
          row.basicNumber = math.format(math.round(math.multiply(math.bignumber(row.operNumber),math.bignumber(row.unitRatio)),2));
          row.allPrice = allPrice !=undefined && allPrice !=null ?allPrice:0;
          row.taxMoney = math.format(math.round(math.multiply(math.bignumber(row.allPrice) ,math.bignumber(row.taxRate) ,math.bignumber(0.01)),2));
          row.taxLastMoney = math.format(math.add(math.bignumber(row.taxMoney),math.bignumber(row.allPrice)));
      },
      calculationPrice(){
        let val = this.form.changeAmount;
         // console.log('value:' + val)
         if (!(/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(val)) {
           this.$modal.msgError("请输入正确收款金额");
           this.form.changeAmount = 0 ;
         } else {
           this.form.backAmount =  math.format(math.subtract(math.bignumber(this.form.changeAmount),math.bignumber(this.form.totalPrice)));
         }
      },
      //商品税点统计
      calRate(row,index){
          this.isTableOut = true;
        // taxRate  taxMoney taxLastMoney
          if(row.allPrice ==null){
            row.taxMoney = 0;
            row.taxLastMoney = 0;
          }else{
            row.taxMoney = math.format(math.round(math.multiply(math.bignumber(row.allPrice), math.bignumber(row.taxRate),math.bignumber(0.01)),2));
            row.taxLastMoney = math.format(math.add(math.bignumber(row.taxMoney) ,math.bignumber(row.allPrice)));
            // this.form.discountLastMoney =
          }
      },
      //优惠统计
      discountTotal(type){
        if(type ==0){
          this.form.discountMoney =  math.format(math.round(math.chain(math.add(math.bignumber(this.form.totalPrice),math.bignumber(this.form.otherMoney))).multiply(math.bignumber(this.form.discount)).multiply(0.01).done(),2));
          this.form.discountLastMoney = math.format(math.chain(math.bignumber(this.form.totalPrice)).subtract(math.bignumber(this.form.discountMoney)).done());
          this.form.debt = 0;
        }else if(type ==1){
          if(this.form.discountLastMoney !=0){
            this.form.discount = math.format(math.round(math.chain(math.bignumber(this.form.discountMoney)).multiply(100).divide(math.bignumber(this.form.totalPrice)).done(),4));
          }
          this.form.discountLastMoney = math.format(math.subtract(math.bignumber(this.form.totalPrice), math.bignumber(this.form.discountMoney)));
          this.form.debt = 0;
        }
      },
      //打卡仓库操作页面 type 0  批量设置仓库  1 新增仓库
      handleDepot(type){
        this.resetDepot();
        this.depot.type = type ;
        this.depot.title = type == 0?'批量设置仓库':'新增仓库';
        this.depot.open = true;
      },
      /** 提交按钮 */
      submitDepotForm(){
          this.$refs["depotForm"].validate(valid => {
            if (valid) {
              let depotId = this.depot.form.id;
              if (this.depot.type == 0 ) {
                this.form.znDepotItemList.forEach(item =>{
                  item.depotId = depotId
                });
                this.$modal.msgSuccess("批量设置仓库成功");
                this.depot.open = false;
              } else {
                addDepot(this.depot.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.depot.open = false;
                  this.getDepots().then(response =>{
                    this.depots =  response.data;
                    this.defaultDepot = this.depots.find(item => item.isDefault==1)
                  });
                });
              }
            }
          });
      },
      cancelDepot(){
         this.depot.open = false;
      },
      //仓库表单重置
      resetDepot(){
        this.depot.form = {
          id: null,
          name: null,
          address: null,
          warehousing: null,
          truckage: null,
          type: null,
          sort: null,
          remark: null,
          principal: null,
          tenantId: null,
          deleteFlag: null,
          isDefault: null
        };
        this.resetForm("depotForm");
      },
  }
};
</script>
<style>
  .el-dialog__body > .el-form > .el-row > div.el-col > div.el-table > .el-table__body-wrapper > table > tbody > .el-table__row > .el-table__cell > .cell{
    padding-left: 1px;
    padding-right: 1px;
  }
  .el-dialog__body > .el-form > .el-row > div.el-col > div.el-table > .el-table__body-wrapper > table > tbody > .el-table__row > .el-table__cell > .cell > .el-input > .el-input__inner{
    padding: 0 2px;
  }
  .el-dialog__body > .el-form > .el-row > div.el-col > div.el-table > .el-table__body-wrapper > table > tbody > .el-table__row > .el-table__cell > .cell > .el-form-item > .el-form-item__content > .el-input-number > .el-input > .el-input__inner {
      padding-left: 0px;
      padding-right: 0px;
  }
  .el-dialog__body > .el-form > .el-row > div.el-col > div.el-table > .el-table__body-wrapper > table > tbody > .el-table__row > .el-table__cell > .cell > .dashed > .el-input__inner{
     border: 1px dashed #DCDFE6;
  }
  .el-dialog__wrapper > .el-dialog > .el-dialog__body > .el-form > .el-row > .el-col-8 .el-form-item > label.el-form-item__label{
        font-size: 18px;
        font-weight: bolder;
        /* width: 150px; */
  }
 /* .el-dialog__wrapper > .el-dialog > .el-dialog__body > .el-form > .el-row > .el-col-8 .el-form-item > div.el-form-item__content{
    margin-left: 150px;
  } */
  .el-dialog__wrapper > .el-dialog > .el-dialog__body > .el-form > .el-row > .el-col-8 .el-form-item > .el-form-item__content > .totalClass > input{
        border-left-width: 0!important;
        border-top-width: 0!important;
        border-right-width: 0!important;
        text-align: center;
        font-size: 28px;
        font-weight: bolder;

  }
  .el-dialog__wrapper > .el-dialog > .el-dialog__body > .el-form > .el-row > .el-col-8 .el-form-item > .el-form-item__content > .totalClass1 > input{
    color: purple;
  }
  .el-dialog__wrapper > .el-dialog > .el-dialog__body > .el-form > .el-row > .el-col-8 .el-form-item > .el-form-item__content > .totalClass2 > input{
    color: red;
  }
  .el-dialog__wrapper > .el-dialog > .el-dialog__body > .el-form > .el-row > .el-col-8 .el-form-item > .el-form-item__content > .totalClass3 > input{
    color: green;
  }
  .el-dialog__wrapper > .el-dialog > .el-dialog__body > .el-form > .el-row > .el-col-8 .el-form-item > .el-form-item__content > .totalClass > input.el-input__inner:hover{
     border-color: #0055ff;
  }
</style>
